import React, { useEffect, useRef, useState } from 'react';
import G6 from '@antv/g6';
import { Modal } from 'antd';
import data from './data.json'

const OrganizationTree: React.FC = () => {
  const ref = useRef<any>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentNode, setCurrentNode] = useState<any>(null);

  useEffect(() => {
    if (!ref.current) return;

    const graph = new G6.TreeGraph({
      container: ref.current,
      width: ref.current.clientWidth,
      height: ref.current.clientHeight,
      modes: {
        default: ['drag-canvas', 'zoom-canvas', 'click-select', 'touch'],
      },
      defaultNode: {
        type: 'rect',
        size: [150, 100], // 调整卡片的大小，使高度大于长度
        style: {
          fill: '#f0f0f0', // 高级灰色背景
          stroke: '#666',
          radius: 10, // 圆角
        },
        labelCfg: {
          style: {
            fill: '#000',
            fontSize: 14,
            position: 'center',
          },
        },
      },
      defaultEdge: {
        type: 'verticle',
        style: {
          stroke: '#ccc',
        },
        getPath(points: any) {
          const startPoint = points[0];
          const endPoint = points[points.length - 1];
          const midPointX = (startPoint.x + endPoint.x) / 2;
          return [
            ['M', startPoint.x, startPoint.y],
            ['L', startPoint.x, midPointX],
            ['L', endPoint.x, midPointX],
            ['L', endPoint.x, endPoint.y],
          ];
        },
      },
      layout: {
        type: 'compactBox',
        direction: 'TB', // 从上到下布局
        getId(d: any) {
          return d.id;
        },
        getHeight: () => 100, // 调整卡片的高度
        getWidth: () => 150, // 调整卡片的宽度
        getVGap: () => 20,
        getHGap: () => 40,
      },
    });

    // 定义自定义节点
    G6.registerNode('custom-node', {
      draw(cfg: any, group: any) {
        const { label, collapsed } = cfg;
        const rect = group.addShape('rect', {
          attrs: {
            x: -75,
            y: -50,
            width: 150,
            height: 100,
            radius: 10,
            fill: '#f0f0f0', // 高级灰色背景
            stroke: '#666',
          },
        });

        // 添加图标
        group.addShape('image', {
          attrs: {
            x: -65,
            y: -40,
            width: 20,
            height: 20,
            img: 'https://img.icons8.com/ios-filled/50/000000/user.png',
          },
        });

        // 添加标签
        group.addShape('text', {
          attrs: {
            x: 0,
            y: 0,
            textAlign: 'center',
            textBaseline: 'middle',
            text: label,
            fill: '#000',
            fontSize: 14,
          },
        });

        // 如果不是首席执行官 (CEO)，则添加删除按钮
        if (cfg.id !== 'root') {
          group.addShape('circle', {
            attrs: {
              x: 55,
              y: -35, // 调整 y 坐标以增加边距
              r: 10,
              fill: '#bfbfbf', // 灰色背景
              cursor: 'pointer',
            },
            name: 'delete-button',
          });

          group.addShape('text', {
            attrs: {
              x: 55,
              y: -35, // 调整 y 坐标以增加边距
              textAlign: 'center',
              textBaseline: 'middle',
              text: 'X',
              fill: '#fff',
              fontSize: 12,
              cursor: 'pointer',
            },
            name: 'delete-button',
          });
        }

        // 添加展开/收缩按钮
        group.addShape('circle', {
          attrs: {
            x: 55,
            y: 35,
            r: 10,
            fill: '#bfbfbf', // 灰色背景
            cursor: 'pointer',
          },
          name: 'collapse-expand-button',
        });

        group.addShape('text', {
          attrs: {
            x: 55,
            y: 35,
            textAlign: 'center',
            textBaseline: 'middle',
            text: collapsed ? '+' : '-', // 根据节点的状态显示不同的文本
            fill: '#fff',
            fontSize: 12,
            cursor: 'pointer',
          },
          name: 'collapse-expand-button',
        });

        return rect;
      },
    });

    graph.node((node: any) => ({
      type: 'custom-node',
      label: node.label,
      id: node.id,
      collapsed: node.collapsed,
    }));

    graph.data(data);
    graph.render();
    graph.fitView();

    // 监听删除按钮的点击事件
    const handleClick = (evt: any) => {
      const { item, target } = evt;
      if (item) {
        const model = item.getModel();
        if (target.get('name') === 'delete-button') {
          graph.removeChild(item.getID());
        } else if (target.get('name') === 'collapse-expand-button') {
          const collapsed = !model.collapsed;
          model.collapsed = collapsed;
          graph.updateItem(item, model);
          graph.layout();
        } else if (target.get('name') !== 'collapse-expand-button' && target.get('name') !== 'delete-button') {
          setCurrentNode(model);
          setModalVisible(true);
        }
      }
    };

    graph.on('node:click', handleClick);
    graph.on('node:touchstart', handleClick);

    return () => {
      graph.off('node:click', handleClick);
      graph.off('node:touchstart', handleClick);
      graph.destroy();
    };
  }, []);

  return (
    <div>
      <div ref={ref} style={{ width: '100%', height: '800px' }} />
      <Modal
        title="详细信息"
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        maskClosable={false} // 点击遮罩层不关闭弹出层
      >
        {currentNode && (
          <div>
            <p>ID: {currentNode.id}</p>
            <p>Label: {currentNode.label}</p>
            {/* 这里可以添加更多详细信息 */}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default OrganizationTree;
